<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace api\common\controllers;

use Yii;
use yii\filters\auth\CompositeAuth;
use yii\filters\ContentNegotiator;
use yii\filters\RateLimiter;
use yii\web\Response;
use zyj\ext\filters\ApiVerbFilter;
use zyj\ext\filters\QueryParamAuth;


class ApiController extends \yii\web\Controller
{
    /**
     * @inheritdoc
     */
    public $enableCsrfValidation = false;


    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'contentNegotiator' => [
                'class' => ContentNegotiator::className(),
                'formats' => [
                    'application/json' => Response::FORMAT_JSON,
                    'application/xml' => Response::FORMAT_XML,
                ],
                'except'=>$this->ResponseExcept()
//                  'only'=>[]
            ],
            'verbFilter' => [
                'class' => ApiVerbFilter::className(),
                'actions' => $this->verbs(),
            ],
//            'authenticator' => [
//                'class' => CompositeAuth::className(),
//                'authMethods'=>[
//                    QueryParamAuth::className(),
//                ],
//                'except'=>$this->authExcepts(),
//                'user'=>$this->authUser(),
//            ],
            'authenticator'=>[
                'class' => QueryParamAuth::className(),
                'except'=>$this->authExcepts(),
                'user'=>$this->authUser(),
            ],
            'rateLimiter' => [
                'class' => RateLimiter::className(),
                'errorMessage'=>'接口调用过于频繁'
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function afterAction($action, $result)
    {
        $result = parent::afterAction($action, $result);
        return $result;
    }

    /**
     * Declares the allowed HTTP verbs.
     * Please refer to [[VerbFilter::actions]] on how to declare the allowed verbs.
     * @return array the allowed HTTP verbs.
     */
    protected function verbs()
    {
        return [
            '*'=>['post']
        ];
    }

    protected function authExcepts(){
        return [];
    }

    protected  function authUser(){
        $module = Yii::$app->controller->module->user;
        return $module;
    }

    protected function ResponseExcept(){
        return [];
    }
}
